package com.seu.project.seuquiz.model.converter;

import com.seu.project.seuquiz.model.dto.contest.ContestTypeInternalAdd;
import com.seu.project.seuquiz.model.dto.contest.ContestUpdateRequest;
import com.seu.project.seuquiz.model.entity.Contest;
import com.seu.project.seuquiz.model.internal.ContestTypeInternal;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author SoftPro
 * @createDate: 2023-07-16 16:11
 */
public class ContestConverter {

    /**
     * ContestUpdateRequest 转化为 Contest
     * @param updateRequest
     * @return
     */
    public static Contest contestUpdateRequestToContest(ContestUpdateRequest updateRequest) {
        if (updateRequest == null) {
            return null;
        }
        String[] res = handleQuestionNum(updateRequest.getQuestionList());

        return Contest.builder()
                .id(updateRequest.getId())
                .contestName(updateRequest.getContestName())
                .startTime(updateRequest.getStartTime())
                .endTime(updateRequest.getEndTime())
                .answerTimes(updateRequest.getAnswerTimes())
                .time(updateRequest.getTime())
                .questionNum(res[0])
                .questionList(res[1])
                .status(updateRequest.getStatus())
                .build();
    }

    private static String[] handleQuestionNum(ContestTypeInternalAdd[] questionList) {
        Map<String, List<Long>> map = Arrays.stream(questionList)
                .collect(Collectors.groupingBy(ContestTypeInternalAdd::getQuestionType,
                        Collectors.mapping(ContestTypeInternalAdd::getId, Collectors.toList())));
        //System.out.println(map);
        String[] res = new String[]{"", ""};

        for (String s : map.keySet()) {
            res[0] += s + map.get(s).size() + "#";
            for (int i = 0; i < map.get(s).size(); i++) {
                res[1] += map.get(s).get(i);
                if (i != map.get(s).size() - 1) {
                    res[1] += ",";
                } else {
                    res[1] += '#';
                }
            }

        }
        res[0] = res[0].substring(0, res[0].length() <= 0 ? 0 : res[0].length() - 1);
        res[1] = res[1].substring(0, res[1].length() <= 0 ? 0 : res[1].length() - 1);
        //        map.keySet().stream()
//                .peek(it -> System.out.println("dsklfdsl;f s"))
//                .peek(it -> res[0] += it + "#")
//                // todo: 测试是否有 []
//                .peek(it -> res[1] += map.get(it).toString().substring(1, map.get(it).toString().length() - 1) + "#");
        // 去掉最后一个#号
        System.out.println(Arrays.toString(res));
//        res[0] = res[0].substring(0, res[0].length() <= 0 ? 0 : res[0].length() - 1);
//        res[1] = res[1].substring(0, res[1].length() <= 0 ? 0 : res[1].length() - 1);
        return res;
    }
}
